<script setup lang="ts">
import {
  getPatientList,
  addPatient,
  editPatient,
  delPatient
} from '@/services/user'
import type { PatientList, Patient } from '@/types/user'
import { computed } from 'vue'
import { ref, onMounted } from 'vue'
import { nameRules, idCardRules } from '@/utils/rules'
import {
  showConfirmDialog,
  type FormInstance,
  showSuccessToast,
  showToast
} from 'vant'
import { useRoute } from 'vue-router'
import { useConsultStore } from '@/stores'
import { useRouter } from 'vue-router'
// import CpNumber from './CpNumber.vue'

const list = ref<PatientList>([])
const loadList = async () => {
  const res = await getPatientList()
  list.value = res.data
  // console.log(list.value, 999)

  if (isChange.value && list.value.length) {
    // 选择患者时  默认选中
    const temp = list.value.find((item) => item.defaultFlag === 1)
    // patientId.value = temp?.id
    if (temp) patientId.value = temp.id
    else patientId.value = list.value[0].id
  }
}

onMounted(() => {
  loadList()
})

// const count = ref(99)

// const bing = ref('month')
// const options = [
//   // CpRadioBtn将来的选项
//   { label: '一周内', value: 'week' },
//   { label: '一个月', value: 'month' },
//   { label: '半年', value: 'halfYear' }
// ]
// const gender = ref(1)
const options = [
  { label: '男', value: 1 },
  { label: '女', value: 0 }
]
// const tang = ref(5)
// const options3 = [
//   { label: '无糖', value: 0 },
//   { label: '五分糖', value: 5 },
//   { label: '七分糖', value: 7 },
//   { label: '全糖', value: 10 }
// ]

const show = ref(false)
const showPopup = (item?: Patient) => {
  if (item) {
    // 编辑
    // 用以前的数据回显 + 多给id标识 添加/编辑
    patient.value = {
      name: item.name,
      idCard: item.idCard,
      defaultFlag: item.defaultFlag,
      gender: item.gender,
      id: item.id
    }
  } else {
    // 添加
    // 数据清空
    patient.value = {
      name: '',
      idCard: '',
      defaultFlag: 0, // 不是默认病人   1 默认病人 true   0 不是默认病人 false
      gender: 1 // 默认男
    }
  }

  show.value = true
}

// 用于表单绑定 => 后端接口保持一致!!!
const patient = ref<Patient>({
  name: '',
  idCard: '',
  defaultFlag: 0, // 不是默认病人   1 默认病人 true   0 不是默认病人 false
  gender: 1 // 默认男
})

// 默认只能get   不能set
// const flag = computed(() => {
//   return patient.value.defaultFlag === 1 ? true : false
// })
const flag = computed({
  get() {
    return patient.value.defaultFlag === 1 ? true : false
  },

  set(value) {
    // console.log(value)
    patient.value.defaultFlag = value ? 1 : 0
  }
})

const form = ref<FormInstance>()
const save = async () => {
  // console.log(11)
  await form.value?.validate() // 整体校验

  // 做身份证号和性别的判定
  const temp = +patient.value.idCard.slice(-2, -1)
  const gender = temp % 2
  console.log(gender)

  if (gender !== patient.value.gender) {
    // 性别不一致 => 提示即可
    await showConfirmDialog({
      title: '温馨提示',
      message: '你确定身份证号正确么?'
    })
  }

  console.log('通过校验')

  patient.value.id
    ? await editPatient(patient.value)
    : await addPatient(patient.value)
  show.value = false
  showSuccessToast(`${patient.value.id ? '编辑' : '添加'}成功`)
  loadList()

  // 发请求 => 关闭弹窗 => 提示 => 重新获取数据
}

const del = async () => {
  // console.log(11)
  await showConfirmDialog({
    title: '温馨提示',
    message: '你确定删除么'
  })

  // 请求
  await delPatient(patient.value.id!)
  showSuccessToast('删除成功')
  loadList()
  show.value = false
}

// ------------------------------------------------------------------------------
const route = useRoute()
const isChange = computed(() => route.query.isChange === '1') // 如果多次使用该计算属性 不会反复计算 直接走缓存

const patientId = ref<string>() // 记录选中患者的id

const store = useConsultStore()
const router = useRouter()
const next = () => {
  if (!patientId.value) return showToast('请选就诊择患者')
  store.setPatient(patientId.value)
  router.push('/consult/pay')
}
</script>

<template>
  <div class="patient-page">
    <cp-nav-bar :title="isChange ? '选择患者' : '家庭档案'"></cp-nav-bar>

    <!-- 头部提示 -->
    <div class="patient-change" v-if="isChange">
      <h3>请选择患者信息</h3>
      <p>以便医生给出更准确的治疗，信息仅医生可见</p>
    </div>

    <div class="patient-list">
      <div
        class="patient-item"
        :class="{ selected: patientId === item.id }"
        @click="patientId = item.id"
        v-for="item in list"
        :key="item.id"
      >
        <div class="info">
          <span class="name">{{ item.name }}</span>
          <span class="id">
            {{ item.idCard.replace(/^(.{6}).+(.{4})$/, '$1******$2') }}
          </span>
          <span>{{ item.genderValue }}</span>
          <span>{{ item.age }}岁</span>
        </div>
        <div class="icon" @click="showPopup(item)">
          <cp-icon name="user-edit" />
        </div>
        <div class="tag" v-if="item.defaultFlag === 1">默认</div>
      </div>

      <div class="patient-add" v-if="list.length < 6" @click="showPopup()">
        <cp-icon name="user-add" />
        <p>添加患者</p>
      </div>

      <div class="patient-tip">最多可添加 6 人</div>
    </div>

    <!-- <van-popup :show="show" @update:show="show = $event">表单</van-popup> -->
    <van-popup v-model:show="show" position="right">
      <!-- 
        由于这次使用cp-nav-bar需要在点击<时 将弹层关闭 => 通过props传递一个函数
       -->
      <cp-nav-bar
        :back="
          () => {
            show = false
          }
        "
        :title="patient.id ? '编辑' : '添加'"
        right-text="保存"
        @click-right="save"
      ></cp-nav-bar>

      <van-form autocomplete="off" ref="form">
        <van-field
          v-model="patient.name"
          label="真实姓名"
          placeholder="请输入真实姓名"
          :rules="nameRules"
        />
        <van-field
          v-model="patient.idCard"
          label="身份证号"
          placeholder="请输入身份证号"
          :rules="idCardRules"
        />
        <van-field label="性别" class="pb4">
          <!-- 单选按钮组件 -->
          <template #input>
            <cp-radio-btn
              :options="options"
              v-model="patient.gender"
            ></cp-radio-btn>
          </template>
        </van-field>
        <van-field label="默认就诊人">
          <template #input>
            <van-checkbox :icon-size="18" v-model="flag" />
          </template>
        </van-field>
      </van-form>

      <!-- 删除按钮 -->

      <van-action-bar v-if="patient.id">
        <van-action-bar-button @click="del">删除</van-action-bar-button>
      </van-action-bar>
    </van-popup>

    <!-- 底部按钮 -->
    <div class="patient-next" v-if="isChange">
      <van-button type="primary" round block @click="next">下一步</van-button>
    </div>
  </div>

  <!-- 封装计数器组件测试v3中v-model -->
  <!-- <CpNumber v-model:count="count"></CpNumber> -->

  <!-- 测试CpRadioBtn组件 -->
  <!-- <CpRadioBtn v-model="bing" :options="options"></CpRadioBtn>
  <CpRadioBtn v-model="gender" :options="options2"></CpRadioBtn>
  <CpRadioBtn v-model="tang" :options="options3"></CpRadioBtn> -->
</template>

<style lang="scss" scoped>
.patient-change {
  padding: 15px;
  > h3 {
    font-weight: normal;
    margin-bottom: 5px;
  }
  > p {
    color: var(--cp-text3);
  }
}
.patient-next {
  padding: 15px;
  background-color: #fff;
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 80px;
  box-sizing: border-box;
}

// 底部操作栏
.van-action-bar {
  padding: 0 10px;
  margin-bottom: 10px;
  .van-button {
    color: var(--cp-price);
    background-color: var(--cp-bg);
  }
}
.patient-page {
  padding: 46px 0 80px;
  :deep() {
    .van-popup {
      width: 100%;
      height: 100%;
      padding-top: 46px;
      box-sizing: border-box;
    }
  }
}
.patient-page {
  padding: 46px 0 80px;
}
.patient-list {
  padding: 15px;
}
.patient-item {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: var(--cp-bg);
  border-radius: 8px;
  margin-bottom: 15px;
  position: relative;
  border: 1px solid var(--cp-bg);
  transition: all 0.3s;
  overflow: hidden;
  .info {
    display: flex;
    flex-wrap: wrap;
    flex: 1;
    span {
      color: var(--cp-tip);
      margin-right: 20px;
      line-height: 30px;
      &.name {
        font-size: 16px;
        color: var(--cp-text1);
        width: 80px;
        margin-right: 0;
      }
      &.id {
        color: var(--cp-text2);
        width: 180px;
      }
    }
  }
  .icon {
    color: var(--cp-tag);
    width: 20px;
    text-align: center;
  }
  .tag {
    position: absolute;
    right: 60px;
    top: 21px;
    width: 30px;
    height: 16px;
    font-size: 10px;
    color: #fff;
    background-color: var(--cp-primary);
    border-radius: 2px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  &.selected {
    border-color: var(--cp-primary);
    background-color: var(--cp-plain);
    .icon {
      color: var(--cp-primary);
    }
  }
}
.patient-add {
  background-color: var(--cp-bg);
  color: var(--cp-primary);
  text-align: center;
  padding: 15px 0;
  border-radius: 8px;
  .cp-icon {
    font-size: 24px;
  }
}
.patient-tip {
  color: var(--cp-tag);
  padding: 12px 0;
}
.pb4 {
  padding-bottom: 4px;
}
</style>
